package com.zhangxi.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhangxi.constant.MessageConstant;
import com.zhangxi.constant.StatusConstant;
import com.zhangxi.dto.DishDTO;
import com.zhangxi.dto.DishPageQueryDTO;
import com.zhangxi.entity.Dish;
import com.zhangxi.entity.DishFlavor;
import com.zhangxi.exception.DeletionNotAllowedException;
import com.zhangxi.mapper.DishFlavorMapper;
import com.zhangxi.mapper.DishMapper;
import com.zhangxi.mapper.SetMealDishMapper;
import com.zhangxi.result.PageResult;
import com.zhangxi.service.DishService;
import com.zhangxi.vo.DishVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: DishServiceImpl
 * Package: com.zhangxi.service.impl
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetMealDishMapper setMealDishMapper;

    /**
     * 菜品新增
     *
     * @param dishDTO
     */
    @Override
    public void insertDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        //属性拷贝
        BeanUtils.copyProperties(dishDTO, dish);
        //插入菜品数据
        dishMapper.insert(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        //获取口味集合
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if (dishFlavors != null && dishFlavors.size() > 0) {
//            增强for写法
//            for (DishFlavor dishFlavor : dishFlavors){
//                dishFlavor.setDishId(dishId);
//            }
            //lambda表达式的写法
            dishFlavors.forEach(dishFlavor -> {
                        dishFlavor.setDishId(dishId);
                    }
            );
            dishFlavorMapper.insertBatch(dishFlavors);
        }
    }

    /**
     * 执行分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //定义分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //执行查询操作
        Page<DishVo> dishes = dishMapper.pageQuery(dishPageQueryDTO);
        //封装查询结果
        PageResult pageResult = new PageResult();
        pageResult.setTotal(dishes.getTotal());
        pageResult.setRecords(dishes.getResult());
        //返回pageResult
        return pageResult;
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除---是否存在起售中的菜品？？
        for (Long id : ids) {
            //根据Id查询菜品
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断当前菜品是否能够删除---是否被套餐关联了？？
        List<Long> setMealDishIds = setMealDishMapper.getSetMealIdsByDishIds(ids);
        log.info("查询的套餐id为：{}",setMealDishIds);
        if (setMealDishIds != null && setMealDishIds.size() >0){
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据
        for (Long id : ids) {
            //删除菜品
            dishMapper.deleteById(id);
            //删除菜品关联的口味
            dishFlavorMapper.deleteByDishId(id);
        }

    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVo getById(Long id) {
        //根据id查询菜品信息
        Dish dish = dishMapper.getById(id);
        //根据id查询口味信息
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        DishVo dishVo = new DishVo();
        //Dish属性的拷贝赋值
        BeanUtils.copyProperties(dish, dishVo);
        dishVo.setFlavors(dishFlavors);
        return dishVo;
    }

    /**
     * 改变菜品的销售状态
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //使用构建者模式构建Dish
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
    }

    /**
     * 更新菜品及更新口味表
     *
     * @param dishDTO
     */
    @Transactional
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        //完成属性的拷贝
        BeanUtils.copyProperties(dishDTO, dish);
        //先更新菜品表
        dishMapper.update(dish);
        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dish.getId());

        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        log.info("口味数据：{}", dishFlavors);
        if (dishFlavors != null && dishFlavors.size() > 0) {
            for (DishFlavor dishFlavor : dishFlavors) {
                //向每条口味记录插入菜品ID
                dishFlavor.setDishId(dish.getId());
            }
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(dishFlavors);
        }
//        lambda表达式法则
        //重新插入口味数据
//        List<DishFlavor> flavors = dishDTO.getFlavors();
//        if (flavors != null && flavors.size() > 0) {
//            flavors.forEach(dishFlavor -> {
//                dishFlavor.setDishId(dishDTO.getId());
//            });
//            //向口味表插入n条数据
//            dishFlavorMapper.insertBatch(flavors);
//        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVo> getByCategoryId(Long categoryId) {
        //List<Dish>  dishes =  dishMapper.getByCategoryId(categoryId);
        //改造dishMapper.getByCategoryId(categoryId);
        Dish dishBuild = Dish.builder()
                .status(StatusConstant.ENABLE)
                .categoryId(categoryId)
                .build();
        List<Dish> dishes = dishMapper.list(dishBuild);
        List<DishVo> dishVoList = new ArrayList<>();
        //对DishVo属性赋值
        for (Dish dish : dishes) {
            DishVo dishVo = new DishVo();
            BeanUtils.copyProperties(dish, dishVo);
            //添加菜品口味表
            List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(dish.getId());
            dishVo.setFlavors(dishFlavors);
            dishVoList.add(dishVo);
        }

        return dishVoList;
    }
}
